"""
Python API调用示例

本文件包含所有API接口的完整调用示例
使用requests库进行HTTP请求
"""

import requests
import json
from typing import Dict, List, Optional


class UserApiClient:
    """用户API客户端类"""
    
    def __init__(self, base_url: str = "http://localhost:8080/api/users"):
        """
        初始化API客户端
        
        Args:
            base_url: API基础地址
        """
        self.base_url = base_url
        self.headers = {
            "Content-Type": "application/json"
        }
    
    def create_user(self, username: str, email: str, password: str) -> Dict:
        """
        创建用户
        
        Args:
            username: 用户名（3-20个字符）
            email: 邮箱地址
            password: 密码（至少6个字符）
            
        Returns:
            创建的用户对象
            
        Raises:
            Exception: 创建失败时抛出异常
        """
        url = self.base_url
        data = {
            "username": username,
            "email": email,
            "password": password
        }
        
        try:
            response = requests.post(url, headers=self.headers, json=data)
            response.raise_for_status()
            result = response.json()
            
            if result["code"] == 200:
                print(f"✅ 创建成功: ID={result['data']['id']}, 用户名={result['data']['username']}")
                return result["data"]
            else:
                raise Exception(result["message"])
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 网络错误: {e}")
            raise
        except Exception as e:
            print(f"❌ 创建失败: {e}")
            raise
    
    def get_all_users(self) -> List[Dict]:
        """
        查询所有用户
        
        Returns:
            用户列表
            
        Raises:
            Exception: 查询失败时抛出异常
        """
        try:
            response = requests.get(self.base_url)
            response.raise_for_status()
            result = response.json()
            
            if result["code"] == 200:
                print(f"✅ 查询成功，共有 {len(result['data'])} 个用户")
                return result["data"]
            else:
                raise Exception(result["message"])
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 网络错误: {e}")
            raise
        except Exception as e:
            print(f"❌ 查询失败: {e}")
            raise
    
    def get_user_by_id(self, user_id: int) -> Dict:
        """
        根据ID查询用户
        
        Args:
            user_id: 用户ID
            
        Returns:
            用户对象
            
        Raises:
            Exception: 查询失败时抛出异常
        """
        url = f"{self.base_url}/{user_id}"
        
        try:
            response = requests.get(url)
            response.raise_for_status()
            result = response.json()
            
            if result["code"] == 200:
                print(f"✅ 查询成功: {result['data']['username']}")
                return result["data"]
            else:
                raise Exception(result["message"])
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 网络错误: {e}")
            raise
        except Exception as e:
            print(f"❌ 查询失败: {e}")
            raise
    
    def get_user_by_username(self, username: str) -> Dict:
        """
        根据用户名查询用户
        
        Args:
            username: 用户名
            
        Returns:
            用户对象
            
        Raises:
            Exception: 查询失败时抛出异常
        """
        url = f"{self.base_url}/username/{username}"
        
        try:
            response = requests.get(url)
            response.raise_for_status()
            result = response.json()
            
            if result["code"] == 200:
                print(f"✅ 查询成功: {result['data']['username']}")
                return result["data"]
            else:
                raise Exception(result["message"])
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 网络错误: {e}")
            raise
        except Exception as e:
            print(f"❌ 查询失败: {e}")
            raise
    
    def update_user(self, user_id: int, username: Optional[str] = None, 
                   email: Optional[str] = None, password: Optional[str] = None) -> Dict:
        """
        更新用户信息
        
        Args:
            user_id: 用户ID
            username: 新用户名（可选）
            email: 新邮箱（可选）
            password: 新密码（可选）
            
        Returns:
            更新后的用户对象
            
        Raises:
            Exception: 更新失败时抛出异常
        """
        url = f"{self.base_url}/{user_id}"
        data = {}
        
        if username:
            data["username"] = username
        if email:
            data["email"] = email
        if password:
            data["password"] = password
        
        try:
            response = requests.put(url, headers=self.headers, json=data)
            response.raise_for_status()
            result = response.json()
            
            if result["code"] == 200:
                print(f"✅ 更新成功: {result['data']['username']}")
                return result["data"]
            else:
                raise Exception(result["message"])
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 网络错误: {e}")
            raise
        except Exception as e:
            print(f"❌ 更新失败: {e}")
            raise
    
    def delete_user(self, user_id: int) -> bool:
        """
        删除用户
        
        Args:
            user_id: 用户ID
            
        Returns:
            是否删除成功
            
        Raises:
            Exception: 删除失败时抛出异常
        """
        url = f"{self.base_url}/{user_id}"
        
        try:
            response = requests.delete(url)
            response.raise_for_status()
            result = response.json()
            
            if result["code"] == 200:
                print(f"✅ 删除成功")
                return True
            else:
                raise Exception(result["message"])
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 网络错误: {e}")
            raise
        except Exception as e:
            print(f"❌ 删除失败: {e}")
            raise


def run_examples():
    """运行完整示例"""
    print("=" * 50)
    print("开始API测试")
    print("=" * 50)
    print()
    
    client = UserApiClient()
    
    try:
        # 1. 创建用户
        print("1. 创建用户...")
        new_user = client.create_user(
            username="johndoe",
            email="john@example.com",
            password="password123"
        )
        print(f"   新用户ID: {new_user['id']}\n")
        
        # 2. 查询所有用户
        print("2. 查询所有用户...")
        all_users = client.get_all_users()
        print(f"   共有 {len(all_users)} 个用户\n")
        
        # 3. 查询指定用户
        print("3. 查询指定用户...")
        user = client.get_user_by_id(new_user["id"])
        print(f"   用户信息: {user['username']} - {user['email']}\n")
        
        # 4. 根据用户名查询
        print("4. 根据用户名查询...")
        user_by_name = client.get_user_by_username("johndoe")
        print(f"   找到用户: {user_by_name['username']}\n")
        
        # 5. 更新用户
        print("5. 更新用户...")
        updated_user = client.update_user(
            new_user["id"],
            username="johndoe2",
            email="john2@example.com",
            password="newpassword123"
        )
        print(f"   更新后: {updated_user['username']}\n")
        
        # 6. 删除用户
        print("6. 删除用户...")
        client.delete_user(new_user["id"])
        print("   删除完成\n")
        
        print("=" * 50)
        print("API测试完成")
        print("=" * 50)
        
    except Exception as e:
        print(f"❌ 测试过程中出现错误: {e}")


# 直接运行示例
if __name__ == "__main__":
    run_examples()

